package com.example.whm;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.LinearLayout;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.model.Comment;
import com.example.whm.model.ZaoDian;

public class EntityDetailComment extends Activity implements OnClickListener{
	AQuery aq;
	String id;
	 AQuery aq2;
	 AQuery aq3;
	 AQuery aq4;
	 TextView mTv;
	 int width;
	 ListView listview;
	 adapter ad;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE); 
		//getSupportActionBar().hide();
		setTheme(R.style.Holo_Theme_Light_NoActionBar);
		setContentView(R.layout.activity_entity_comment);
		// webview=(WebView) findViewById(R.id.entity_detail_web);
		//webview.getSettings().setBuiltInZoomControls(false);
		 aq=new AQuery(this);
		 //LinearLayout line=(LinearLayout)getLayoutInflater().inflate(R.layout.activity_entity_detail);
		 LinearLayout line2=(LinearLayout) findViewById(R.id.entity_detail_line);
		 aq2=new AQuery(this,line2);
		  listview=(ListView) aq.find(R.id.entity_detail_comment_listview).getListView();
		  aq.id(R.id.entity_detail_comment_post).clicked(this);
		/* LinearLayout line3=(LinearLayout) findViewById(R.id.entity_detail_line_cont);
		 LinearLayout line4=(LinearLayout) findViewById(R.id.entity_detail_line_comment);
		 mTv= (TextView) findViewById(R.id.entity_detail_cont); 
		 aq3=new AQuery(this,line3);
		 Display display = getWindowManager().getDefaultDisplay(); 
		 width = display.getWidth();  
		 ImageView iv=aq2.id(R.id.entity_detail_image).getImageView();
		 iv.setMaxWidth(width-32);
		 iv.setMaxHeight(180);
		 iv.setScaleType(ImageView.ScaleType.FIT_XY);
		 iv.setAdjustViewBounds(true);	 
		 aq4=new AQuery(this,line4);
		 aq4.id(R.id.entity_detail_line_comm_more).clicked(this);
		 
		 
		 
		 */
		 
		 Bundle b= getIntent().getExtras();
		 if (b!=null) {
			 Log.i("EntityDetail", "getIntent().getExtras()  id="+b.getString("id"));
			 id=b.getString("id");
			 init(id);
		}
	   
	
		 
	}

	

	public void init(String id){
		if (id!=null) {
			
			String url = "http://"+Whm_app.api_url+":9000/api/detail_zaodian/"+id;
			Log.i("EntityDetail", "url="+url);
			aq.ajax(url, String.class, -1, this, "parsedata");
		}
		
		
	}
	
	public void parsedata(String url, String s, AjaxStatus status){
		 if (s!=null) {
			 JSONObject json=JSON.parseObject(s);
			 JSONObject j=JSON.parseObject(json.getString("result"));
			// System.out.println("zao==========="+j.getString("zao"));
			 ZaoDian z=JSON.parseObject(j.getString("zao"), ZaoDian.class);
			 List<Comment> list=JSON.parseArray(j.getString("comments"), Comment.class);
			 
	/*		 System.out.println("========================="+s);
			 System.out.println("========================="+list.size());
			 
			 String imgurl=z.getPre_pic().replace("localhost", Whm_app.api_url);
			// System.out.println(imgurl);
			 aq.id(R.id.entity_detail_top).id(R.id.entity_detail_top_title).text(z.getName());
			// int w=aq2.id(R.id.entity_detail_image).getImageView().getWidth();
			
			//Toast.makeText(EntityDetail.this, String.valueOf(width-32), 1000).show();
			 aq2.id(R.id.entity_detail_image).image(imgurl, true, true, 200, R.drawable.ic_launcher, null, 0, AQuery.RATIO_PRESERVE);
	 
			 aq2.id(R.id.entity_detail_name).text(z.getName());
			 aq2.id(R.id.entity_detail_pri).text(String.valueOf(z.getPrice()));
			 aq2.id(R.id.entity_detail_like).text(String.valueOf(z.getLike_num()));
		
			 TextView t= (TextView) aq3.id(R.id.entity_detail_cont).getTextView();
			imageget getter= new imageget(aq2, this,500,500,t);
			 Spanned span=Html.fromHtml(z.getDetail(),getter,null);			
			 t.setText(span);*/
			 //webview.loadData(z.getDetail(), "text/html", "utf-8");
			 
			 ad=new adapter(list);
			 listview.setAdapter(ad);
			 
			 
			 
		}
		
	}
	  class adapter extends BaseAdapter{

			
			List<Comment> list;
			public adapter() {
				super();
				// TODO Auto-generated constructor stub
			}
		   
			public List<Comment> getList(){
				
				return this.list;
			}
			public adapter(List<Comment> list) {
				super();
				this.list = list;
			}


			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return list.size();
			}

			@Override
			public Object getItem(int arg0) {
				// TODO Auto-generated method stub
				return list.get(arg0);
			}

			@Override
			public long getItemId(int arg0) {
				// TODO Auto-generated method stub
				return arg0;
			}

			@Override
			public View getView(int arg0, View arg1, ViewGroup arg2) {
				// TODO Auto-generated method stub
			
				System.out.println("arg0---------------"+arg0);
				if(arg1 == null){
					arg1 = aq.inflate(arg1, R.layout.entity_detail_comment_listview_item, arg2);
				}
				
				
				Comment i = (Comment) getItem(arg0);
				
				AQuery aq = aq2.recycle(arg1);
				aq.id(R.id.entity_detail_comment_listview_item_author).text(i.getUsername());
				aq.id(R.id.entity_detail_comment_listview_item_date).text(i.getCreatetime());
				aq.id(R.id.entity_detail_comment_listview_item_cont).text(i.getDetail());
				
				/*TextView t=(TextView) aq.id(R.id.entity_detail_listview_item_comm).getTextView();
				imageget getter= new imageget(aq, EntityDetailComment.this,200,200,t);
				 Spanned span=Html.fromHtml(i.getDetail(),getter,null);		
				
				 t.setText(span);*/
			     
				
				return arg1;
			}
			
			
		}
	
	
	
	
	
	class imageget implements Html.ImageGetter{
		AQuery t;
		Context c;
		URLDrawable urlDrawable;
		int w;
		int h;
		TextView view;
		public imageget(AQuery t, Context c) {
			super();
			this.t = t;
			this.c = c;
		}
		public imageget(AQuery t, Context c,int w,int h,TextView view) {
			super();
			this.t = t;
			this.c = c;
			this.w=w;
			this.h=h;
			this.view=view;
		}
		@Override
		public Drawable getDrawable(String source) {
			 final LevelListDrawable d2 = new LevelListDrawable();
			  // LinearLayout layout= (LinearLayout) EntityDetail.this.getLayoutInflater().inflate(R.layout.entity_text_bg);
			//   LayoutParams params = layout.getLayoutParams();
			 LinearLayout.LayoutParams Params = 
					   new LinearLayout.LayoutParams(100, 100); 
			   
			   LinearLayout line= new LinearLayout(EntityDetailComment.this);
			   line.setLayoutParams(Params);
			   line.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
			// Changes the height and width to the specified *pixels*
		
		        Drawable empty =  line.getBackground();
		        //		new BitmapDrawable(convertViewToBitmap(v, 500));
			
		        
		        d2.addLevel(0, 0, empty);
		        d2.setBounds(0, 0, w, h);
		        
		       final Bitmap b=aq.getCachedImage(source);
		        
		       // System.out.println("b==null ========"+(b==null));
		        if (b!=null) {
		        	//aq.cache(source, 200000);
		        	System.out.println("b==null ========"+(b==null));
		        	// Bitmap bt=Utility.decodeSampledBitmapFromResource(Utility.bitmap2byte(b), w, h);
		        	 BitmapDrawable d = new BitmapDrawable(b);
		                d2.addLevel(1, 1, d);
		                d2.setBounds(0, 0, w, h);
		                d2.setLevel(1);
		                return d2;
		        	
				}else{
					final String src=source;
					 //Toast.makeText(EntityDetail.this, String.valueOf("aaaaaaaaaaaa"), 1000).show();
				/*	 new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							
							try {
								URL url = new URL(src);
								 Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
								 BitmapDrawable d = new BitmapDrawable(bitmap);
					                d2.addLevel(1, 1, d);
					                
					                d2.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
					                d2.setLevel(1);
					                
					                runOnUiThread( new Runnable() {
										public void run() {
											Toast.makeText(EntityDetail.this, String.valueOf(aq2==null), 1000).show();
				                             // CharSequence c=aq2.id(R.id.entity_detail_cont).getTextView().getText();
				                              //aq2.id(R.id.entity_detail_cont).text(c);
											// LinearLayout line2=(LinearLayout) findViewById(R.id.entity_detail_line);
											// aq2=new AQuery(EntityDetail.this,line2);
											 ((TextView)findViewById(R.id.entity_detail_cont)).invalidate();
				                             // aq2.id()
				                              Toast.makeText(EntityDetail.this, String.valueOf("eeeeeee"), 1000).show();
										}
									});    
					                
							
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							
							
							
						}
					}).start();*/
					 final String s=source;
					 new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							
							 try {
									Thread.sleep(2000);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								 
							refresh(d2, s,w,h,view);
							
							
							
						}
					}).start();
					
					 
					 return d2;
					
				}
                
		        
		}
		
	}
	
	public void refresh(LevelListDrawable d,String source,int wi,int he,TextView v){
		final int w=wi;
		final int h=he;
		final LevelListDrawable d2=d;
		final TextView view=v;
		if (source.indexOf("http://")==-1) {
			source=Whm_app.api_url_pref+source;
		};
		
		aq.ajax(source, Bitmap.class,0,new AjaxCallback<Bitmap>(){
            
            @Override
			public void callback(String url, final Bitmap bitmap, AjaxStatus status) {
                    
                    if(bitmap != null){
        
                  	  runOnUiThread( new Runnable() {
								@Override
								public void run() {
									
		                             // CharSequence c=aq2.id(R.id.entity_detail_cont).getTextView().getText();
		                              //aq2.id(R.id.entity_detail_cont).text(c);
									// LinearLayout line2=(LinearLayout) findViewById(R.id.entity_detail_line);
									// aq2=new AQuery(EntityDetail.this,line2);
									 //Bitmap bt=Utility.decodeSampledBitmapFromResource(Utility.bitmap2byte(bitmap), w, h);
									 BitmapDrawable d = new BitmapDrawable(bitmap);
									 Toast.makeText(EntityDetailComment.this, bitmap.getWidth()+" "+bitmap.getHeight(), 1000).show();
						                d2.addLevel(1, 1, d);
						                d2.setBounds(0, 0, w, h);
						                d2.setLevel(1);
									   // CharSequence t = view.getText();
									   
									    //view.setText(t);			
									    view.postInvalidate();
		                             // aq2.id()
		                              Toast.makeText(EntityDetailComment.this, String.valueOf("eeeeeee"), 1000).show();
								}
							});    
                    }else{
                       
                    }
            }
            
    });
		
		
	}
	
	
	
	public Drawable LayoutToDrawable( View v ){         
		Bitmap snapshot = null;
	    Drawable drawable = null;
	    v.setDrawingCacheEnabled(true);
	    v.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW); //Quality of the snpashot
	    try {
	        snapshot = Bitmap.createBitmap(v.getDrawingCache()); // You can tell how to crop the snapshot and whatever in this method
	        drawable = new BitmapDrawable(snapshot);
	    } finally {
	        v.setDrawingCacheEnabled(false);
	    }
	    return drawable;
     }

public static Bitmap convertViewToBitmap(View view, int size) {
      view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
      MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
      int width = size*40;

      view.layout(0, 0, width, view.getMeasuredHeight());  //根据字符串的长度显示view的宽度
      view.buildDrawingCache();
      Bitmap bitmap = view.getDrawingCache();
      return bitmap;
}
	
	
	
	
	
	
	
	
	
	
	
	public class URLDrawable extends BitmapDrawable {
	    // the drawable that you need to set, you could set the initial drawing
	    // with the loading image if you need to
	    protected Drawable drawable=new BitmapDrawable();

	    @Override
	    public void draw(Canvas canvas) {
	        // override the draw to facilitate refresh function later
	        if(drawable != null) {
	            drawable.draw(canvas);
	        }
	    }
	}
	
	
	class LoadImage extends AsyncTask<Object, Void, Bitmap> {

        private LevelListDrawable mDrawable;

        @Override
        protected Bitmap doInBackground(Object... params) {
            String source = (String) params[0];
            mDrawable = (LevelListDrawable) params[1];
           
            try {
                InputStream is = new URL(source).openStream();
                return BitmapFactory.decodeStream(is);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
  
            if (bitmap != null) {
                BitmapDrawable d = new BitmapDrawable(bitmap);
                mDrawable.addLevel(1, 1, d);
                mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                mDrawable.setLevel(1);
                // i don't know yet a better way to refresh TextView
                // mTv.invalidate() doesn't work as expected
                CharSequence t = mTv.getText();
                mTv.setText(t);
            }
        }
    }
	
	
	
	
	
	
	
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.entity_detail, menu);
		return true;
	}



	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.entity_detail_comment_post:
			 String cont=aq.id(R.id.entity_detail_comment_input).getText().toString().trim();
			 aq.id(R.id.entity_detail_comment_input).clear();
			 if (cont.length()>0) {
				 comment_post(cont);
			}else{
				Toast.makeText(EntityDetailComment.this, "comment content isn't null", 1000).show();
				
			}
			break;

		default:
			break;
		}
	}

	public void comment_post(String cont){
		
		  Map<String, Object> params = new HashMap<String, Object>();
		    params.put("id", id);
		    params.put("detail", cont);
		   
		  
		    System.out.println("buy_sure===="+JSON.toJSONString(params));
		    String url="http://"+Whm_app.api_url+":9000/api/add_comment_func";
		  AjaxCallback<String> cb = new AjaxCallback<String>();        
		  cb.url(url).type(String.class).weakHandler(this, "comment_func_result");
		  SharedPreferences sp=((Application)getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
		String cookiename=sp.getString("cookie_name",null);
		String cookievalue=sp.getString("cookie_value",null);
		
		if (cookiename!=null&&cookievalue!=null) {
			cb.cookie(cookiename,cookievalue);   
			cb.params(params);
			aq.ajax(cb);
		}else{
			Bundle b=new Bundle();
			b.putString("skip", "0");	
			Intent i=new Intent(EntityDetailComment.this, Login.class);
		    i.putExtras(b);
			startActivity(i);
		}
		
		
	}	
	public void comment_func_result(String url, String r, AjaxStatus status){
		
		if (status.getCode()==200) {
			 if (r!=null) {
				 JSONObject json=JSON.parseObject(r);
				 
				 JSONObject j=JSON.parseObject(json.getString("item"));
				 Comment comm= JSON.parseObject(j.getString("comm"), Comment.class);
			     ad.getList().add(comm);
			     ad.notifyDataSetChanged();
			     listview.setSelection(ad.getList().size()-1);
			 }
		}
	}
	
}
